import java.io.*;
import java.util.*;

/*
 ID: ning yusui
 LANG: JAVA
 TASK: comehome
 */

public class comehome {
    public static final int INF = 1000 * 1000 * 1000;
    Scanner in;
    PrintWriter out;
    public static final int SIZE = 52;


    public comehome() throws IOException {
        in = new Scanner(new File(this.getClass().getName() + ".in"));
        out = new PrintWriter(new BufferedWriter(new FileWriter(this.getClass().getName() +
                ".out")));
    }

    private void work() {
        int dijMat[][] = new int[SIZE][SIZE];
        input(dijMat);
        floyd(dijMat);
        outPut(dijMat);
        out.flush();
        out.close();
    }

    private void input(int[][] dijMat) {
        for (int[] a : dijMat) Arrays.fill(a, INF);
        int edges = in.nextInt();
        for (int i = 0; i < edges; i++) {
            int uPoint = inputPoint();
            int vPoint = inputPoint();
            int w = in.nextInt();
            if (dijMat[uPoint][vPoint] > w) dijMat[uPoint][vPoint] = dijMat[vPoint][uPoint] = w;
        }
    }

    private void outPut(int[][] dijMat) {
        int shortest = INF;
        int shortestIndex = -1;
        int startPoint = calcIndex('Z');
        for (int i = calcIndex('A'); i < startPoint; i++)
            if (dijMat[startPoint][i] < shortest) {
                shortest = dijMat[startPoint][i];
                shortestIndex = i;
            }
        char ch = (char) ('A' + shortestIndex-26);
        out.println(ch + " " + shortest);
    }

    private void floyd(int[][] dijMat) {
        for (int i = 0; i < SIZE; i++)
            for (int j = 0; j < SIZE; j++)
                for (int k = 0; k < SIZE; k++)
                    if (dijMat[j][k] > dijMat[j][i] + dijMat[i][k])
                        dijMat[j][k] = dijMat[j][i] + dijMat[i][k];
    }

    private int inputPoint() {
        char u = in.next().charAt(0);
        return calcIndex(u);
    }

    private int calcIndex(char u) {
        int index;
        if (Character.isUpperCase(u)) {
            index = u - 'Z' + SIZE - 1;
        } else {
            index = u - 'a';
        }
        return index;
    }

    public static void main(String[] args) throws IOException {
        new comehome().work();
    }
}
